import React, { useEffect, useState, useRef } from 'react';
import { View, Text, StyleSheet, SafeAreaView, ActivityIndicator, TextInput, TouchableOpacity, Animated, ScrollView, Image, FlatList, RefreshControl, Modal, Dimensions } from 'react-native';
import { Toast } from '@ant-design/react-native';
import Header from '../../../components/Header';
import { getDeviceRepairListApi, getAllRoomApi, saveDeviceRepairApi } from './api';
import CustomQRScanner from '../../../components/CustomQRScanner';
import PortalDropdown from '../../../components/PortalDropdown';
import saoma from '../../../assets/saoma.png';
import xiala from '../../../assets/xiala.png';

interface DeviceRepairReportProps {
    onNavigateToLogin?: () => void;
    onBackPress?: () => void;
    onNavigateToScreen?: (route: string, id: string) => void;
}

const DeviceRepairReport: React.FC<DeviceRepairReportProps> = ({ onNavigateToLogin, onBackPress, onNavigateToScreen }) => {
    const [loading, setLoading] = useState(true);
    const [repairData, setRepairData] = useState<any>(null);
    const [repairList, setRepairList] = useState<any[]>([]);
    const [search, setSearch] = useState('');
    const [scanVisible, setScanVisible] = useState(false);
    const [roomList, setRoomList] = useState<any[]>([]);
    const [selectedRooms, setSelectedRooms] = useState<string[]>([]);
    const [selectedStates, setSelectedStates] = useState<number[]>([]);
    const [selectedLevels, setSelectedLevels] = useState<number[]>([]);
    const [roomDropdownVisible, setRoomDropdownVisible] = useState(false);
    const [stateDropdownVisible, setStateDropdownVisible] = useState(false);
    const [levelDropdownVisible, setLevelDropdownVisible] = useState(false);
    const [roomArrowRotation] = useState(new Animated.Value(0));
    const [stateArrowRotation] = useState(new Animated.Value(0));
    const [levelArrowRotation] = useState(new Animated.Value(0));

    // Portal 下拉框的 ref
    const roomTriggerRef = useRef<View>(null);
    const stateTriggerRef = useRef<View>(null);
    const levelTriggerRef = useRef<View>(null);
    const modalLevelTriggerRef = useRef<View>(null);

    // 新增报修单模态框相关状态
    const [addRepairModalVisible, setAddRepairModalVisible] = useState(false);
    const [deviceNum, setDeviceNum] = useState('');
    const [errorDesc, setErrorDesc] = useState('');
    const [selectedLevel, setSelectedLevel] = useState(3);
    const [modalLevelDropdownVisible, setModalLevelDropdownVisible] = useState(false);
    const [levelArrowRotationModal] = useState(new Animated.Value(0));
    // 新增：模态框扫码相关状态
    const [modalScanVisible, setModalScanVisible] = useState(false);
    // 图片全屏显示相关状态
    const [imageModalVisible, setImageModalVisible] = useState(false);
    const [selectedImage, setSelectedImage] = useState<string>('');

    // 分页相关状态
    const [current, setCurrent] = useState(1);
    const [size] = useState(10);
    const [hasMore, setHasMore] = useState(true);
    const [loadingMore, setLoadingMore] = useState(false);
    const [refreshing, setRefreshing] = useState(false);

    // 状态映射
    const REPAIR_STATE_MAP: { [key: number]: string } = {
        1: '待诊断',
        2: '已诊断',
        3: '维修中',
        4: '待评价',
        5: '已评价',
    };

    // 状态选项
    const REPAIR_STATE_OPTIONS = [
        { value: 1, label: '待诊断' },
        { value: 2, label: '已诊断' },
        { value: 3, label: '维修中' },
        { value: 4, label: '待评价' },
        { value: 5, label: '已评价' },
    ];

    // 紧急程度映射
    const URGENCY_LEVEL_MAP: { [key: number]: string } = {
        1: '十万火急',
        2: '非常紧急',
        3: '一般紧急',
        4: '不紧急',
    };

    // 紧急程度选项
    const URGENCY_LEVEL_OPTIONS = [
        { value: 1, label: '十万火急' },
        { value: 2, label: '非常紧急' },
        { value: 3, label: '一般紧急' },
        { value: 4, label: '不紧急' },
    ];

    useEffect(() => {
        loadDeviceRepairList();
        loadRoomList();
    }, []);

    const loadRoomList = async () => {
        try {
            const result = await getAllRoomApi();
            setRoomList(result?.data || []);
        } catch (error) {
            console.log('获取车间列表失败:', error);
        }
    };

    // 搜索设备报修列表
    const loadDeviceRepairList = async (
        keyword: string = search,
        roomIdList: string[] = selectedRooms,
        stateList: number[] = selectedStates,
        levelList: number[] = selectedLevels,
        isLoadMore: boolean = false
    ) => {
        if (isLoadMore) {
            setLoadingMore(true);
        } else {
            setLoading(true);
            setCurrent(1);
            setHasMore(true);
        }

        try {
            const result = await getDeviceRepairListApi({
                current: isLoadMore ? current + 1 : 1,
                size,
                room_id_list: roomIdList,
                state_list: stateList,
                level_list: levelList,
                keyword
            });

            const newRecords = result?.data?.records || [];
            const total = result?.data?.total || 0;

            if (isLoadMore) {
                setRepairList(prev => [...prev, ...newRecords]);
                setCurrent(prev => prev + 1);
            } else {
                setRepairList(newRecords);
                setCurrent(1);
            }

            // 判断是否还有更多数据
            const totalLoaded = isLoadMore ? repairList.length + newRecords.length : newRecords.length;
            setHasMore(totalLoaded < total);

            setRepairData(result?.data || null);
        } catch (error) {
            console.log('获取设备报修列表失败:', error);
            if (!isLoadMore) {
                setRepairList([]);
            }
        } finally {
            if (isLoadMore) {
                setLoadingMore(false);
            } else {
                setLoading(false);
            }
        }
    };

    // 滑动到底部加载更多
    const handleLoadMore = () => {
        if (hasMore && !loadingMore && !loading) {
            loadDeviceRepairList(search, selectedRooms, selectedStates, selectedLevels, true);
        }
    };

    // 下拉刷新
    const handleRefresh = async () => {
        setRefreshing(true);
        await loadDeviceRepairList(search, selectedRooms, selectedStates, selectedLevels, false);
        setRefreshing(false);
    };

    // 搜索处理
    const handleSearchChange = (text: string) => {
        setSearch(text);
        clearTimeout((global as any).searchTimeout);
        (global as any).searchTimeout = setTimeout(() => {
            loadDeviceRepairList(text, selectedRooms, selectedStates, selectedLevels, false);
        }, 500);
    };

    // 扫码处理
    const onScanPress = () => {
        setScanVisible(true);
    };

    // 新增报修单处理
    const handleAddRepair = () => {
        setAddRepairModalVisible(true);
    };



    // 模态框紧急程度选择处理
    const handleModalLevelToggle = (levelValue: number) => {
        setSelectedLevel(levelValue);
        setModalLevelDropdownVisible(false);
    };

    // 切换模态框紧急程度下拉框显示状态
    const toggleModalLevelDropdown = () => {
        const toValue = modalLevelDropdownVisible ? 0 : 1;
        setModalLevelDropdownVisible(!modalLevelDropdownVisible);
        Animated.timing(levelArrowRotationModal, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();
    };

    // 确认新增报修单
    const handleConfirmAddRepair = async () => {
        try {
            const requestData = {
                device_num: deviceNum,
                error_desc: errorDesc,
                level: selectedLevel,
                report_link_list: []
            };


            const response = await saveDeviceRepairApi(requestData);

            // 显示成功提示
            Toast.success('新增报修单成功', 1);

            // 成功后关闭模态框并刷新列表
            setAddRepairModalVisible(false);
            setDeviceNum('');
            setErrorDesc('');
            setSelectedLevel(3);

            // 刷新列表
            loadDeviceRepairList();
        } catch (error) {
            console.error('新增报修单失败:', error);
            Toast.fail('新增报修单失败，请重试', 1);
        }
    };

    // 取消新增报修单
    const handleCancelAddRepair = () => {
        setAddRepairModalVisible(false);
        setDeviceNum('');
        setErrorDesc('');
        setSelectedLevel(3);
    };

    const onBarcodeScan = (data: string) => {
        setScanVisible(false);
        setSearch(data);
        // 扫码后立即搜索
        loadDeviceRepairList(data, selectedRooms, selectedStates, selectedLevels, false);
    };

    // 车间选择处理
    const handleRoomToggle = (roomId: string) => {
        setSelectedRooms(prev => {
            const newRooms = prev.includes(roomId)
                ? prev.filter(id => id !== roomId)
                : [...prev, roomId];
            setTimeout(() => {
                loadDeviceRepairList(search, newRooms, selectedStates, selectedLevels, false);
            }, 100);
            return newRooms;
        });
    };

    // 状态选择处理
    const handleStateToggle = (stateValue: number) => {
        setSelectedStates(prev => {
            const newStates = prev.includes(stateValue)
                ? prev.filter(s => s !== stateValue)
                : [...prev, stateValue];
            setTimeout(() => {
                loadDeviceRepairList(search, selectedRooms, newStates, selectedLevels, false);
            }, 100);
            return newStates;
        });
    };

    // 紧急程度选择处理
    const handleLevelToggle = (levelValue: number) => {
        setSelectedLevels(prev => {
            const newLevels = prev.includes(levelValue)
                ? prev.filter(l => l !== levelValue)
                : [...prev, levelValue];
            setTimeout(() => {
                loadDeviceRepairList(search, selectedRooms, selectedStates, newLevels, false);
            }, 100);
            return newLevels;
        });
    };

    // 切换下拉框显示状态
    const toggleRoomDropdown = () => {
        const toValue = roomDropdownVisible ? 0 : 1;
        setRoomDropdownVisible(!roomDropdownVisible);
        Animated.timing(roomArrowRotation, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();
    };

    const toggleStateDropdown = () => {
        const toValue = stateDropdownVisible ? 0 : 1;
        setStateDropdownVisible(!stateDropdownVisible);
        Animated.timing(stateArrowRotation, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();
    };

    const toggleLevelDropdown = () => {
        const toValue = levelDropdownVisible ? 0 : 1;
        setLevelDropdownVisible(!levelDropdownVisible);
        Animated.timing(levelArrowRotation, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();
    };

    // 获取显示文本
    const getRoomDisplayText = () => {
        if (selectedRooms.length === 0) return '车间';
        if (selectedRooms.length === 1) {
            const room = roomList.find(r => r.id === selectedRooms[0]);
            return room ? `${room.dept_name}` : '车间';
        }
        return `已选${selectedRooms.length}项`;
    };

    const getStateDisplayText = () => {
        if (selectedStates.length === 0) return '状态';
        if (selectedStates.length === 1) {
            const state = REPAIR_STATE_MAP[selectedStates[0]];
            return state || '未知';
        }
        return `已选${selectedStates.length}项`;
    };

    const getLevelDisplayText = () => {
        if (selectedLevels.length === 0) return '紧急程度';
        if (selectedLevels.length === 1) {
            const level = URGENCY_LEVEL_MAP[selectedLevels[0]];
            return level || '未知';
        }
        return `已选${selectedLevels.length}项`;
    };

    // 获取报修状态样式
    const getRepairStateStyle = (state: number) => {
        switch (state) {
            case 1: // 待诊断 - 橙色边框
                return {
                    ...styles.statusText,
                    borderWidth: 1,
                    color: '#ff6600',
                    borderColor: '#ff6600',
                    paddingHorizontal: 8,
                    paddingVertical: 4,
                    borderRadius: 4
                };
            case 2: // 已诊断 - 绿色边框
                return {
                    ...styles.statusText,
                    borderWidth: 1,
                    color: '#00aa00',
                    borderColor: '#00aa00',
                    paddingHorizontal: 8,
                    paddingVertical: 4,
                    borderRadius: 4
                };
            case 3: // 维修中 - 红色边框
                return {
                    ...styles.statusText,
                    borderWidth: 1,
                    color: '#ff4444',
                    borderColor: '#ff4444',
                    paddingHorizontal: 8,
                    paddingVertical: 4,
                    borderRadius: 4
                };
            case 4: // 待评价 - 橙色边框
                return {
                    ...styles.statusText,
                    borderWidth: 1,
                    color: '#ff6600',
                    borderColor: '#ff6600',
                    paddingHorizontal: 8,
                    paddingVertical: 4,
                    borderRadius: 4
                };
            case 5: // 已评价 - 绿色边框
                return {
                    ...styles.statusText,
                    borderWidth: 1,
                    color: '#00aa00',
                    borderColor: '#00aa00',
                    paddingHorizontal: 8,
                    paddingVertical: 4,
                    borderRadius: 4
                };
            default:
                return {
                    ...styles.statusText,
                    borderWidth: 1,
                    color: '#888888',
                    borderColor: '#888888',
                    paddingHorizontal: 8,
                    paddingVertical: 4,
                    borderRadius: 4
                };
        }
    };

    // 渲染报修项
    const renderRepairItem = ({ item }: { item: any }) => (
        <TouchableOpacity onPress={() => {
            (global as any).deviceRepairDetailId = item.id;
            onNavigateToScreen && onNavigateToScreen('Device/DeviceRepairReport/DeviceRepairReportDetail', item.id);
        }}>
            <View style={styles.repairCard}>
                <View style={styles.cardHeader}>
                    <View style={styles.deviceInfo}>
                        <TouchableOpacity
                            style={styles.imageContainer}
                            onPress={() => {
                                setSelectedImage(item.device_link ? String(item.device_link) : '');
                                setImageModalVisible(true);
                            }}
                        >
                            <Image
                                source={item.device_link ? { uri: String(item.device_link) } : require('../../../assets/zwtp.png')}
                                style={styles.deviceImg}
                                resizeMode="contain"
                            />
                        </TouchableOpacity>
                        <Text style={styles.deviceNum}>{item.device_num}</Text>
                    </View>
                    <Text style={getRepairStateStyle(item.state)}>{REPAIR_STATE_MAP[item.state] || '未知'}</Text>
                </View>
                <View style={styles.cardDetails}>
                    <View style={styles.detailRowGroup}>
                        <View style={styles.detailItemVertical}>
                            <Text style={styles.detailLabel}>维修人</Text>
                            <Text style={styles.detailValue}>{item.repair_user_name || '无'}</Text>
                        </View>
                        <View style={styles.detailItemVertical1}>
                            <Text style={styles.detailLabel}>报修单号</Text>
                            <Text style={styles.detailValue}>{item.repair_num}</Text>
                        </View>
                    </View>
                </View>
                <View style={styles.cardFooter}>
                    <Text style={styles.dateText}>报修日期: {item.create_time}</Text>
                </View>
            </View>
        </TouchableOpacity>
    );

    return (
        <SafeAreaView style={styles.container}>
            <Header
                title="设备报修"
                showBackButton={true}
                showAddButton={true}
                onNavigateToLogin={onNavigateToLogin}
                onBackPress={onBackPress}
                onAddPress={handleAddRepair}
            />
            {/* 顶部搜索和筛选区 */}
            <View style={styles.topBar}>
                <View style={styles.inputContainer}>
                    <TextInput
                        style={styles.searchInput}
                        placeholder="请输入设备名称或编号搜索"
                        placeholderTextColor="#999"
                        value={search}
                        onChangeText={handleSearchChange}
                    />
                    {search.length > 0 && (
                        <TouchableOpacity
                            style={styles.clearButton}
                            onPress={() => {
                                setSearch('');
                                loadDeviceRepairList();
                            }}
                        >
                            <Text style={styles.clearButtonText}>×</Text>
                        </TouchableOpacity>
                    )}
                </View>
                <TouchableOpacity style={styles.scanBtn} onPress={onScanPress}>
                    <Image source={saoma} style={{ width: 30, height: 30 }} />
                </TouchableOpacity>
            </View>
            <View style={styles.filterBar}>
                <View style={styles.dropdownContainer}>
                    <TouchableOpacity
                        ref={roomTriggerRef}
                        style={styles.filterBtn}
                        onPress={toggleRoomDropdown}
                    >
                        <Text style={styles.filterBtnText}>{getRoomDisplayText()}</Text>
                        <Animated.Image
                            source={xiala}
                            style={[
                                styles.arrowIcon,
                                {
                                    transform: [{
                                        rotate: roomArrowRotation.interpolate({
                                            inputRange: [0, 1],
                                            outputRange: ['0deg', '180deg']
                                        })
                                    }]
                                }
                            ]}
                        />
                    </TouchableOpacity>
                    <PortalDropdown
                        visible={roomDropdownVisible}
                        onClose={() => {
                            setRoomDropdownVisible(false);
                            // 关闭时重置动画
                            Animated.timing(roomArrowRotation, {
                                toValue: 0,
                                duration: 200,
                                useNativeDriver: true,
                            }).start();
                        }}
                        options={roomList.map(room => ({ value: room.id, label: room.dept_name }))}
                        selectedValues={selectedRooms}
                        onSelect={handleRoomToggle}
                        triggerRef={roomTriggerRef}
                        placeholder="车间"
                        multiple={true}
                    />
                </View>
                <View style={styles.dropdownContainer}>
                    <TouchableOpacity
                        ref={stateTriggerRef}
                        style={styles.filterBtn}
                        onPress={toggleStateDropdown}
                    >
                        <Text style={styles.filterBtnText}>{getStateDisplayText()}</Text>
                        <Animated.Image
                            source={xiala}
                            style={[
                                styles.arrowIcon,
                                {
                                    transform: [{
                                        rotate: stateArrowRotation.interpolate({
                                            inputRange: [0, 1],
                                            outputRange: ['0deg', '180deg']
                                        })
                                    }]
                                }
                            ]}
                        />
                    </TouchableOpacity>
                    <PortalDropdown
                        visible={stateDropdownVisible}
                        onClose={() => {
                            setStateDropdownVisible(false);
                            // 关闭时重置动画
                            Animated.timing(stateArrowRotation, {
                                toValue: 0,
                                duration: 200,
                                useNativeDriver: true,
                            }).start();
                        }}
                        options={REPAIR_STATE_OPTIONS}
                        selectedValues={selectedStates}
                        onSelect={handleStateToggle}
                        triggerRef={stateTriggerRef}
                        placeholder="状态"
                        multiple={true}
                    />
                </View>
                <View style={styles.dropdownContainer}>
                    <TouchableOpacity
                        ref={levelTriggerRef}
                        style={styles.filterBtn}
                        onPress={toggleLevelDropdown}
                    >
                        <Text style={styles.filterBtnText}>{getLevelDisplayText()}</Text>
                        <Animated.Image
                            source={xiala}
                            style={[
                                styles.arrowIcon,
                                {
                                    transform: [{
                                        rotate: levelArrowRotation.interpolate({
                                            inputRange: [0, 1],
                                            outputRange: ['0deg', '180deg']
                                        })
                                    }]
                                }
                            ]}
                        />
                    </TouchableOpacity>
                    <PortalDropdown
                        visible={levelDropdownVisible}
                        onClose={() => {
                            setLevelDropdownVisible(false);
                            // 关闭时重置动画
                            Animated.timing(levelArrowRotation, {
                                toValue: 0,
                                duration: 200,
                                useNativeDriver: true,
                            }).start();
                        }}
                        options={URGENCY_LEVEL_OPTIONS}
                        selectedValues={selectedLevels}
                        onSelect={handleLevelToggle}
                        triggerRef={levelTriggerRef}
                        placeholder="紧急程度"
                        multiple={true}
                    />
                </View>
            </View>
            {loading ? (
                <View style={styles.loadingContainer}>
                    <ActivityIndicator size="large" color="#0076ff" />
                    <Text style={styles.loadingText}>搜索中...</Text>
                </View>
            ) : (
                <FlatList
                    data={repairList}
                    keyExtractor={item => item.id}
                    renderItem={renderRepairItem}
                    contentContainerStyle={{ padding: 10 }}
                    onEndReached={handleLoadMore}
                    onEndReachedThreshold={0.1}
                    refreshControl={
                        <RefreshControl
                            refreshing={refreshing}
                            onRefresh={handleRefresh}
                            colors={['#0076ff']}
                            tintColor="#0076ff"
                        />
                    }
                    ListEmptyComponent={
                        <View style={styles.emptyContainer}>
                            <Image
                                source={require('../../../assets/zwsj.png')}
                                style={styles.emptyImage}
                                resizeMode="contain"
                            />
                            <Text style={styles.emptyText}>暂无报修数据</Text>
                        </View>
                    }
                    ListFooterComponent={
                        loadingMore ? (
                            <View style={styles.loadingMoreContainer}>
                                <ActivityIndicator size="small" color="#0076ff" />
                                <Text style={styles.loadingMoreText}>加载更多...</Text>
                            </View>
                        ) : null
                    }
                />
            )}
            {/* 扫码模态框 */}
            <Modal visible={scanVisible} animationType="slide">
                <CustomQRScanner
                    onRead={onBarcodeScan}
                    onClose={() => setScanVisible(false)}
                />
            </Modal>

            {/* 新增报修单扫码模态框 - 移到最外层确保不被遮挡 */}
            <Modal
                visible={modalScanVisible}
                animationType="slide"
                transparent={false}
                onShow={() => console.log('扫码模态框显示了')}
                onRequestClose={() => {
                    console.log('扫码模态框请求关闭');
                    setModalScanVisible(false);
                }}
            >
                <CustomQRScanner
                    onRead={(data: string) => {
                        console.log('扫码成功:', data);
                        setModalScanVisible(false);
                        setDeviceNum(data);
                        // 扫码成功后重新打开新增报修单模态框
                        setTimeout(() => {
                            setAddRepairModalVisible(true);
                        }, 100);
                    }}
                    onClose={() => {
                        console.log('扫码模态框关闭');
                        setModalScanVisible(false);
                        // 关闭扫码模态框后重新打开新增报修单模态框
                        setTimeout(() => {
                            setAddRepairModalVisible(true);
                        }, 100);
                    }}
                />
            </Modal>

            {/* 新增报修单模态框 */}
            <Modal visible={addRepairModalVisible} animationType="fade" transparent={true}>
                <View style={styles.modalOverlay}>
                    <View style={styles.modalContent}>
                        <View style={styles.modalHeader}>
                            <Text style={styles.modalTitle}>新增报修单</Text>
                        </View>

                        <ScrollView style={styles.modalBody} showsVerticalScrollIndicator={false}>
                            {/* 扫码输入区域 */}
                            <View style={styles.scanInputContainer}>
                                <TouchableOpacity
                                    style={styles.scanIcon}
                                    onPress={() => {
                                        console.log('扫码按钮被点击了');
                                        console.log('当前 modalScanVisible:', modalScanVisible);
                                        // 先关闭新增报修单模态框，再打开扫码模态框
                                        setAddRepairModalVisible(false);
                                        setTimeout(() => {
                                            setModalScanVisible(true);
                                            console.log('设置 modalScanVisible 为 true');
                                        }, 100);
                                    }}
                                >
                                    <Image source={saoma} style={{ width: 28, height: 28, }} />
                                </TouchableOpacity>
                                <TextInput
                                    style={styles.scanInput}
                                    placeholder="请扫物料二维码"
                                    placeholderTextColor="#999"
                                    value={deviceNum}
                                    onChangeText={setDeviceNum}
                                />
                                {deviceNum.length > 0 && (
                                    <TouchableOpacity
                                        style={styles.clearButton}
                                        onPress={() => setDeviceNum('')}
                                    >
                                        <Text style={styles.clearButtonText1}>×</Text>
                                    </TouchableOpacity>
                                )}
                            </View>

                            {/* 紧急程度选择 */}
                            <View style={styles.levelContainer}>
                                <Text style={styles.levelLabel}>紧急程度</Text>
                                <TouchableOpacity
                                    style={styles.levelSelector}
                                    onPress={toggleModalLevelDropdown}
                                >
                                    <Text style={styles.levelText}>
                                        {URGENCY_LEVEL_MAP[selectedLevel] || '请选择'}
                                    </Text>
                                    <Animated.Image
                                        source={xiala}
                                        style={[
                                            styles.levelArrow,
                                            {
                                                transform: [{
                                                    rotate: levelArrowRotationModal.interpolate({
                                                        inputRange: [0, 1],
                                                        outputRange: ['0deg', '180deg']
                                                    })
                                                }]
                                            }
                                        ]}
                                    />
                                </TouchableOpacity>
                                {modalLevelDropdownVisible && (
                                    <View style={styles.modalLevelDropdown}>
                                        {URGENCY_LEVEL_OPTIONS.map(option => (
                                            <TouchableOpacity
                                                key={option.value}
                                                style={styles.modalLevelOption}
                                                onPress={() => handleModalLevelToggle(option.value)}
                                            >
                                                <Text style={styles.modalLevelOptionText}>
                                                    {option.label}
                                                </Text>
                                            </TouchableOpacity>
                                        ))}
                                    </View>
                                )}
                            </View>

                            {/* 故障现象输入 */}
                            <View style={styles.faultContainer}>
                                <Text style={styles.faultLabel}>故障现象</Text>
                                <TextInput
                                    style={styles.faultInput}
                                    placeholder="请输入故障描述"
                                    placeholderTextColor="#999"
                                    value={errorDesc}
                                    onChangeText={setErrorDesc}
                                    multiline={true}
                                    numberOfLines={4}
                                    maxLength={240}
                                />
                                <Text style={styles.charCount}>{errorDesc.length}/240</Text>
                            </View>
                        </ScrollView>

                        {/* 按钮区域 */}
                        <View style={styles.modalButtonContainer}>
                            <TouchableOpacity style={styles.cancelButton} onPress={handleCancelAddRepair}>
                                <Text style={styles.cancelButtonText}>取消</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.confirmButton} onPress={handleConfirmAddRepair}>
                                <Text style={styles.confirmButtonText}>确定</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>

            {/* 图片全屏显示模态框 */}
            <Modal visible={imageModalVisible} transparent={true} animationType="fade">
                <View style={styles.imageModalContainer}>
                    <TouchableOpacity
                        style={styles.imageModalOverlay}
                        onPress={() => setImageModalVisible(false)}
                    >
                        <Image
                            source={selectedImage ? { uri: selectedImage } : require('../../../assets/zwtp.png')}
                            style={styles.fullScreenImage}
                            resizeMode="contain"
                        />
                    </TouchableOpacity>
                </View>
            </Modal>
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    topBar: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 10,
        paddingTop: 10,
    },
    filterBar: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        paddingHorizontal: 10,
        marginTop: 10,
        marginBottom: 10,
    },
    inputContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
        position: 'relative',
    },
    searchInput: {
        flex: 1,
        height: 40,
        backgroundColor: '#fff',
        borderRadius: 17,
        paddingHorizontal: 16,
        paddingRight: 40,
        paddingVertical: 8,
        fontSize: 15,
        marginRight: 10,
    },
    clearButton: {
        position: 'absolute',
        right: 8,
        top: 0,
        bottom: 0,
        justifyContent: 'center',
        alignItems: 'center',
        width: 30,
        height: 30,
    },
    clearButtonText: {
        color: '#999',
        fontSize: 18,
        fontWeight: 'bold',
        textAlign: 'center',
        textAlignVertical: 'center',
        lineHeight: 40,
        includeFontPadding: false,
        paddingTop: 0,
        paddingBottom: 0,
    },
    clearButtonText1: {
        color: '#999',
        fontSize: 18,
        fontWeight: 'bold',
        textAlign: 'center',
        textAlignVertical: 'center',
        lineHeight: 47,
        includeFontPadding: false,
        paddingTop: 0,
        paddingBottom: 0,
    },
    scanBtn: {
        width: 40,
        height: 40,
        borderRadius: 20,
        backgroundColor: '#fff',
        justifyContent: 'center',
        alignItems: 'center',
        borderWidth: 1,
        borderColor: '#eee',
    },
    dropdownContainer: {
        position: 'relative',
        flex: 1,
        marginHorizontal: 2,
    },
    filterBtn: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        backgroundColor: '#fff',
        borderRadius: 17,
        paddingVertical: 8,
        paddingHorizontal: 12,
        borderWidth: 1,
        borderColor: '#eee',
        minHeight: 36,
    },
    filterBtnText: {
        color: '#333',
        fontSize: 16,
    },
    dropdownMenu: {
        position: 'absolute',
        top: 35,
        left: 0,
        right: 0,
        backgroundColor: '#fff',
        borderRadius: 8,
        borderWidth: 1,
        borderColor: '#ddd',
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.15,
        shadowRadius: 6,
        elevation: 4,
        zIndex: 1000,
        maxHeight: 200,
    },
    dropdownOption: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingVertical: 12,
        paddingHorizontal: 15,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
    },
    dropdownOptionSelected: {
        // 选中状态样式
    },

    dropdownOptionText: {
        fontSize: 16,
        color: '#333',
    },
    dropdownOptionTextSelected: {
        color: '#0076ff',
        fontWeight: 'bold',
    },
    checkmark: {
        fontSize: 20,
        color: '#0076ff',
        textAlignVertical: 'center',
        includeFontPadding: false,
    },
    arrowIcon: {
        width: 16,
        height: 16,
        marginLeft: 5,
    },
    loadingContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    loadingText: {
        marginTop: 10,
        fontSize: 16,
        color: '#666',
    },
    loadingMoreContainer: {
        paddingVertical: 20,
        alignItems: 'center',
    },
    loadingMoreText: {
        marginTop: 10,
        fontSize: 14,
        color: '#666',
    },
    content: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        padding: 20,
    },
    text: {
        fontSize: 18,
        color: '#333',
    },
    dataText: {
        fontSize: 14,
        color: '#666',
        marginTop: 10,
    },
    repairCard: {
        backgroundColor: '#fff',
        borderRadius: 10,
        marginBottom: 14,
        padding: 12,
        shadowColor: '#000',
        shadowOpacity: 0.04,
        shadowRadius: 4,
        shadowOffset: { width: 0, height: 2 },
        elevation: 2,
    },
    cardHeader: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: 8,
    },
    deviceInfo: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
    },
    deviceImg: {
        width: 60,
        height: 60,
        borderRadius: 8,
        marginRight: 12,
        backgroundColor: '#f0f0f0',
    },
    imageContainer: {
        position: 'relative',
        zIndex: 10,
    },
    deviceImgPlaceholder: {
        width: 60,
        height: 60,
        borderRadius: 8,
        backgroundColor: '#f0f0f0',
        justifyContent: 'center',
        alignItems: 'center',
        marginRight: 12,
    },
    placeholderText: {
        fontSize: 12,
        color: '#999',
    },
    deviceNum: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#222',
    },
    statusText: {
        fontSize: 14,
        color: '#666',
    },
    cardDetails: {
        marginTop: 8,
        backgroundColor: '#f8f8f8',
        borderRadius: 8,
        padding: 12,
        paddingHorizontal: 15,
    },
    detailRowGroup: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginBottom: 6,
        paddingHorizontal: 0,
    },
    detailItemVertical: {
        flex: 0,
        width: '24%',
    },
    detailItemVertical1: {
        flex: 0,
        width: '70%',
    },
    detailLabel: {
        fontSize: 13,
        color: '#666',
        marginBottom: 4,
    },
    detailValue: {
        fontSize: 12,
        color: '#333',
        textAlign: 'left',
    },
    cardFooter: {
        marginTop: 8,
        paddingTop: 8,
        borderTopWidth: 1,
        borderTopColor: '#eee',
    },
    dateText: {
        fontSize: 12,
        color: '#999',
    },
    emptyContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        paddingVertical: 50,
    },
    emptyImage: {
        width: 200,
        height: 200,
        marginBottom: 16,
    },
    emptyText: {
        fontSize: 16,
        color: '#999',
    },
    // 模态框样式
    modalOverlay: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'flex-end',
    },
    modalContent: {
        backgroundColor: '#fff',
        // borderRadius: 12,
        width: '100%',
        height: '80%',
        position: 'absolute',
        bottom: 0,
        zIndex: 1000,
        flexDirection: 'column',
    },
    modalHeader: {
        padding: 20,
        paddingBottom: 10,
    },
    modalBody: {
        flex: 1,
        paddingHorizontal: 20,
        paddingBottom: 20,
    },
    modalTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#333',
        textAlign: 'center',
        marginBottom: 20,
    },
    scanInputContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        borderBottomWidth: 1,
        borderBottomColor: '#007AFF',
        paddingBottom: 8,
        marginBottom: 20,
    },
    scanIcon: {
        marginRight: 10,
        padding: 5,
    },
    scanIconText: {
        fontSize: 20,
    },
    scanInput: {
        flex: 1,
        fontSize: 16,
        color: '#333',
        paddingRight: 35,
    },
    levelContainer: {
        marginBottom: 20,
        position: 'relative',
        zIndex: 10000,
    },
    levelLabel: {
        fontSize: 16,
        color: '#333',
        marginBottom: 8,
    },
    levelSelector: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingVertical: 12,
        paddingHorizontal: 15,
        borderWidth: 1,
        borderColor: '#ddd',
        borderRadius: 8,
    },
    levelText: {
        fontSize: 16,
        color: '#333',
    },
    levelArrow: {
        width: 16,
        height: 16,
    },
    modalLevelDropdown: {
        position: 'absolute',
        top: 70,
        left: 0,
        right: 0,
        backgroundColor: '#fff',
        borderRadius: 8,
        borderWidth: 1,
        borderColor: '#ddd',
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.15,
        shadowRadius: 6,
        elevation: 10,
        zIndex: 9999,
    },
    modalLevelOption: {
        paddingVertical: 12,
        paddingHorizontal: 15,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
    },
    modalLevelOptionText: {
        fontSize: 16,
        color: '#333',
    },
    faultContainer: {
        marginBottom: 20,
    },
    faultLabel: {
        fontSize: 16,
        color: '#333',
        marginBottom: 8,
    },
    faultInput: {
        borderWidth: 1,
        borderColor: '#ddd',
        borderRadius: 8,
        padding: 12,
        fontSize: 16,
        color: '#333',
        minHeight: 100,
        textAlignVertical: 'top',
    },
    charCount: {
        fontSize: 12,
        color: '#999',
        textAlign: 'right',
        marginTop: 4,
    },
    modalButtonContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        padding: 20,
        paddingTop: 10,
        borderTopWidth: 1,
        borderTopColor: '#eee',
        backgroundColor: '#fff',
    },
    cancelButton: {
        flex: 1,
        paddingVertical: 12,
        paddingHorizontal: 20,
        borderWidth: 1,
        borderColor: '#007AFF',
        borderRadius: 8,
        marginRight: 10,
        alignItems: 'center',
    },
    cancelButtonText: {
        fontSize: 16,
        color: '#007AFF',
    },
    confirmButton: {
        flex: 1,
        paddingVertical: 12,
        paddingHorizontal: 20,
        backgroundColor: '#007AFF',
        borderRadius: 8,
        marginLeft: 10,
        alignItems: 'center',
    },
    confirmButtonText: {
        fontSize: 16,
        color: '#fff',
    },
    imageModalContainer: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.9)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    imageModalOverlay: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        width: '100%',
        height: '100%',
    },
    fullScreenImage: {
        width: Dimensions.get('window').width,
        height: Dimensions.get('window').height,
    },
});

export default DeviceRepairReport; 